import bpy
from typing import Union, List
from bpy.types import Object, Context
from .get_common_vars import get_common_vars


def create_modifier(ob: Object, name: str, type_name: str, position=None):

    if name in ob.modifiers:
        last_mod = ob.modifiers.get(name)
    else:
        ob.modifiers.new(name=name, type=type_name)
        last_mod = ob.modifiers[-1]

    if position:
        bpy.ops.object.modifier_move_to_index(modifier=name, index=position)

    return last_mod


def get_object_from_scene(name: str) -> Object:
    view_layer = get_common_vars(get_view_layer=True)
    return view_layer.objects.get(name, None)


def remove_modifier_from_object(object: Union[Object, str], type: str = 'FLUID', first: bool = False):

    if object and isinstance(object, str):
        object = get_object_from_scene(object)

    if not object:
        return

    for mod in object.modifiers:
        if mod.type == type:
            object.modifiers.remove(mod)
            if first:
                break


def remove_modifier_from_active_object(context:Context, type: str = 'FLUID', once: bool = False):
    remove_modifier_from_object(context.active_object, type, once)


def generic_copy(source, target) -> None:
    blacklist = ["__doc__", "__module__", "__slots__", "bl_rna"]
    # if attribute is not in black list, and is not readonly (with dir get all modifier attributes):
    [setattr(target, attr, getattr(source, attr)) for attr in dir(source) if attr not in blacklist and not target.is_property_readonly(attr)]


def copy_modifier_by_name_from_active_to_selected(context:Context, white_list_mods:List[str]) -> None:

    """ copiamos los modificadores de la lista blanca del objeto activo a la seleccion """
    
    ob_active = context.active_object

    if not ob_active or len(context.selected_objects) <= 0 or len(white_list_mods) <= 0:
        return

    for ob in context.selected_objects:
        
        for org_modifier in ob_active.modifiers:
            
            org_mod_name = org_modifier.name
            
            if org_mod_name not in white_list_mods or org_mod_name in ob.modifiers:
                continue
        
            org_mod_type = org_modifier.type
            new_modifier = ob.modifiers.new(type=org_mod_type, name=org_mod_name)

            if new_modifier:
                generic_copy(org_modifier, new_modifier)